package com.city.itis.dao.impl;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.city.itis.dao.HobbyDao;
import com.city.itis.domain.Hobby;

/**
 * 爱好Dao实现类
 * @author WY
 *
 */
@Component("hobbyDao")
public class HobbyDaoImpl implements HobbyDao 
{
	
	private HibernateTemplate hibernateTemplate;
	public HibernateTemplate getHibernateTemplate()
	{
		return hibernateTemplate;
	}
	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) 
	{
		this.hibernateTemplate = hibernateTemplate;
	}


	@Override
	public int save(Hobby hobby) 
	{
		
		try
		{
			int id=(Integer)this.hibernateTemplate.save(hobby);
			return id;
			
		}catch(Exception e)
		{
			return 0;
		}
	}

	@Override
	public int delete(Hobby hobby) 
	{
		try {
			this.hibernateTemplate.delete(hobby);
		} catch (Exception e) {
		return 0;
		}
		return 1;
	}

	@Override
	public int deleteById(Integer id) 
	{
		Hobby hobby=(Hobby) this.getHibernateTemplate().get(Hobby.class, id);
		if(hobby!=null){
		try {
			this.hibernateTemplate.delete(hobby);
		} catch (Exception e) {
			return 0;
		}
		return 1;
		}
		return 0;
	}

	@Override
	public int update(Hobby hobby) 
	{
		try {
			this.hibernateTemplate.update(hobby);
		} catch (Exception e) {
			return 0;
		}
		return 1;
	}

	@Override
	public Hobby getHobbyById(Integer id) 
	{
		Hobby hobby=(Hobby)this.getHibernateTemplate().get(Hobby.class, id);
	     if(hobby!=null){
	    	 return hobby;
	     }
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Hobby getHobbyByName(String name) {

		String queryString="FROM Hobby h where h.name=? ";
		List<Hobby> hobbyList=(List<Hobby>)this.getHibernateTemplate().find(queryString,name);
		if(hobbyList!=null)
		{
			for(Hobby h:hobbyList)
			{
				return h;
			}
		}
		return null;
	}

	@Override
	public List<Hobby> findAll() 
	{
		String queryString="FROM Hobby order by id desc ";
		@SuppressWarnings("unchecked")
		List<Hobby> hobbyList=(List<Hobby>)this.hibernateTemplate.find(queryString);
		if(hobbyList!=null){
			return hobbyList;
		}
		return null;
	}
	
	
}
